package com.zidian.teacher.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.ManageGroupAdapter;
import com.zidian.teacher.bean.GroupListBean;
import com.zidian.teacher.bean.ListGroupBean;
import com.zidian.teacher.bean.ListStudyBean;
import com.zidian.teacher.bean.PutGroupBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ProgressBarBlackUtil;
import com.zidian.teacher.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/7 0007.
 * <p>
 * 小组管理  编辑删除和添加小组
 */
public class GroupManageActivity extends ToolBarActivity {

    @Bind(R.id.group_recycler)
    RecyclerView groupRecycler;
    private ImageButton backBtn;
    private LinearLayoutManager mGroupLayoutManager;
    private ManageGroupAdapter groupAdapter;
    private List<ListGroupBean> groupBeanList = new ArrayList<>();
    private String courseId;
    private PutGroupBean putBeans = new PutGroupBean();
    private boolean hasChange = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_study_group_manage);
        setTitle("分组管理");
        ButterKnife.bind(this);
        backBtn = (ImageButton) findViewById(R.id.toolbar_back);
        courseId = getIntent().getStringExtra("courseId");
        getGroupMessage();
        initView();
    }

    private void initView() {

        groupAdapter = new ManageGroupAdapter(this, groupBeanList);

        mGroupLayoutManager = new LinearLayoutManager(this);

        groupRecycler.setLayoutManager(mGroupLayoutManager);

        groupRecycler.setAdapter(groupAdapter);


        groupAdapter.setOnItemClickListener(new ManageGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {


                if (position == groupBeanList.size()) {
                    final Dialog alertDialog = new Dialog(context);
                    alertDialog.show();
                    Window window = alertDialog.getWindow();
                    window.setBackgroundDrawable(new ColorDrawable(0));
                    window.setContentView(R.layout.global_edit_dialog);
                    final EditText et = (EditText) window.findViewById(R.id.group_add_edit);
                    TextView cancel = (TextView) window.findViewById(R.id.dia_cancle);
                    TextView sure = (TextView) window.findViewById(R.id.dia_sure);
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.cancel();
                        }
                    });
                    sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (et.getText().toString().trim().length() <= 0) {
                                Snackbar.make(et, "请输入小组名",Snackbar.LENGTH_SHORT).show();
                            } else {
                                alertDialog.cancel();
                                addGroup(et.getText().toString().trim());
                            }
                        }
                    });
                } else {
                }


            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });

        groupAdapter.setOnButtonClickListener(new ManageGroupAdapter.OnButtonClickListener() {
            @Override
            public void onDeleteBtnClick(int position) {
                deleteGroup(position);
            }

            @Override
            public void onEditBtnClick(int position) {
                Intent intent = new Intent();
                putBeans.getGroupBeans().clear();
                putBeans.getGroupBeans().add(groupBeanList.get(position));
                putBeans.getGroupBeans().add(groupBeanList.get(groupBeanList.size() - 1));
                intent.setClass(context, EditGroupActivity.class);
                intent.putExtra("groupBean", putBeans);
                ((GroupManageActivity) context).startActivityForResult(intent, 6000);
            }
        });

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("hasChange", hasChange);
                setResult(5001, intent);
                finish();
            }
        });


    }

    private void addGroup(final String groupingName) {
        String loginUrl = Constant.URL_GOAL + "grouping/add";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("groupingName", groupingName);
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
                        hasChange = true;
                        groupBeanList.clear();
                        getGroupMessage();
                        return;
                    }

                } catch (JSONException e) {

                }
            }
        });
    }

    private void getGroupMessage() {

        String loginUrl = Constant.URL_GOAL + "work/student";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("className", "");
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                GroupListBean model = gson.fromJson(response, GroupListBean.class);
                if (model.isSuccess()) {
                    initData(model);
                }

            }
        });
    }

    private void initData(GroupListBean model) {

        for (int i = 0; i < model.getData().size(); i++) {
            List<ListStudyBean> group = new ArrayList<>();
            if (model.getData().get(i).getGroup() != null)
                for (int j = 0; j < model.getData().get(i).getGroup().size(); j++) {
                    group.add(new ListStudyBean(model.getData().get(i).getGroup().get(j).getStudentHeadPortrait(), model.getData().get(i).getGroup().get(j).getStudentName(), model.getData().get(i).getGroup().get(j).getStudentId(), model.getData().get(i).getGroup().get(j).getGroupId(), false));
                }
            ListGroupBean g = new ListGroupBean(model.getData().get(i).getGroupingName(), group.size() + "", model.getData().get(i).getGroupingId(), false, group);
            groupBeanList.add(g);
        }
        groupAdapter.notifyDataSetChanged();
    }


    private void deleteGroup(int position) {
        String loginUrl = Constant.URL_GOAL + "grouping/del";
        HashMap<String, String> map = new HashMap<>();
        map.put("groupingId", groupBeanList.get(position).getGroupingId());
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        getGroupMessage();
                        return;
                    } else {
                        ToastUtil.showToast(context, "删除小组成功！");
                        hasChange = true;
                        groupBeanList.clear();
                        getGroupMessage();
                        return;
                    }

                } catch (JSONException e) {

                }
            }
        });

    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6000) {
            if (resultCode == 6001) {
                hasChange = data.getBooleanExtra("hasChange", false);
                if (hasChange) {
                    groupBeanList.clear();
                    getGroupMessage();
                }
            }
        }
    }
}
